package com.gitee.xmhzzz.component.snowflake.core.snowflake;

import com.gitee.xmhzzz.component.spring.util.ApplicationContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.ArrayList;
import java.util.List;

/**
 * 使用 Redis 获取雪花 WorkId
 *
 */
@Slf4j
public class RedisWorkIdChoose extends AbstractWorkIdChooseTemplate implements InitializingBean {
    
    private RedisTemplate stringRedisTemplate;
    
    public RedisWorkIdChoose() {
        this.stringRedisTemplate = ApplicationContextUtil.getBean(StringRedisTemplate.class);
    }
    
    @Override
    public WorkIdWrapper chooseWorkId() {
        DefaultRedisScript redisScript = new DefaultRedisScript();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/workIdLua.lua")));
        List<Long> luaResultList = null;
        try {
            redisScript.setResultType(List.class);
            luaResultList = (ArrayList) this.stringRedisTemplate.execute(redisScript, null);
        } catch (Exception ex) {
            log.error("Redis Lua 脚本获取 WorkId 失败", ex);
        }
        return  new WorkIdWrapper(luaResultList.get(0), luaResultList.get(1));
    }
    
    @Override
    public void afterPropertiesSet() throws Exception {
        chooseAndInit();
    }
}
